package com.miaoshaproject.validator;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Created by kenny on 2019/1/6.
 */
@Component
public class ValidationImpl implements InitializingBean{
    private Validator validator;

    public ValidationResult validate(Object bean){

        final ValidationResult validationResult = new ValidationResult();

        final Set<ConstraintViolation<Object>> constraintValidatorSet = validator.validate(bean);
        if(constraintValidatorSet.size()>0){
            validationResult.setHasErrors(true);
            constraintValidatorSet.forEach(constraintValidtion->{
                String errMsg = constraintValidtion.getMessage();
                String propertyName = constraintValidtion.getPropertyPath().toString();
                validationResult.getErrorMsgMap().put(propertyName,errMsg);

            });
        }
        return validationResult;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.validator = Validation.buildDefaultValidatorFactory().getValidator();

    }
}
